// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.apache.doris.nereids.rules.rewrite;

import org.apache.doris.nereids.rules.Rule;
import org.apache.doris.nereids.rules.RuleType;
import org.apache.doris.nereids.trees.expressions.AssertNumRowsElement;
import org.apache.doris.nereids.trees.expressions.AssertNumRowsElement.Assertion;
import org.apache.doris.nereids.trees.plans.Plan;
import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate;
import org.apache.doris.nereids.trees.plans.logical.LogicalAssertNumRows;
import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
import org.apache.doris.nereids.trees.plans.logical.LogicalJoin;
import org.apache.doris.nereids.trees.plans.logical.LogicalLimit;
import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
import org.apache.doris.nereids.trees.plans.logical.LogicalSort;

/** EliminateAssertNumRows */
public class EliminateAssertNumRows extends OneRewriteRuleFactory {

    @Override
    public Rule build() {
        return logicalAssertNumRows()
                .then(assertNumRows -> {
                    Plan checkPlan = assertNumRows.child();
                    while (skipPlan(checkPlan) != checkPlan) {
                        checkPlan = skipPlan(checkPlan);
                    }
                    return canEliminate(assertNumRows, checkPlan) ? assertNumRows.child() : null;
                }).toRule(RuleType.ELIMINATE_ASSERT_NUM_ROWS);
    }

    private Plan skipPlan(Plan plan) {
        if (plan instanceof LogicalProject || plan instanceof LogicalFilter || plan instanceof LogicalSort) {
            plan = plan.child(0);
        } else if (plan instanceof LogicalJoin) {
            if (((LogicalJoin<?, ?>) plan).getJoinType().isLeftSemiOrAntiJoin()) {
                plan = plan.child(0);
            } else if (((LogicalJoin<?, ?>) plan).getJoinType().isRightSemiOrAntiJoin()) {
                plan = plan.child(1);
            }
        }
        return plan;
    }

    private boolean canEliminate(LogicalAssertNumRows<?> assertNumRows, Plan plan) {
        long maxOutputRowcount;
        AssertNumRowsElement assertNumRowsElement = assertNumRows.getAssertNumRowsElement();
        Assertion assertion = assertNumRowsElement.getAssertion();
        long assertNum = assertNumRowsElement.getDesiredNumOfRows();
        // Don't need to consider TopN, because it's generated by Sort + Limit.
        if (plan instanceof LogicalLimit) {
            maxOutputRowcount = ((LogicalLimit<?>) plan).getLimit();
        } else if (plan instanceof LogicalAggregate && ((LogicalAggregate<?>) plan).getGroupByExpressions().isEmpty()) {
            if (assertion == Assertion.EQ && assertNum == 1) {
                return true;
            } else {
                maxOutputRowcount = 1;
            }
        } else {
            return false;
        }

        switch (assertion) {
            case NE:
            case LT:
                if (maxOutputRowcount < assertNum) {
                    return true;
                }
                break;
            case LE:
                if (maxOutputRowcount <= assertNum) {
                    return true;
                }
                break;
            default:
                return false;
        }
        return false;
    }
}
